<?php

namespace Api\Event;


/** 
 * 打赏接口
 * @author liubo <liubo@ilongyuan.com>
 */

class RewardEvent extends BaseEvent 
{

    /**
     * 打赏
     * @author liubo <liubo@ilongyuan.com.cn>
     * @param  integer $uid       user_id
     * @param  integer $target_id 
     * @param  string  $type      video/comment
     * @param  integer $money     金额
     */
    public function doReward($uid, $target_id, $type, $money)
    {
        \Think\Log::record("[REWARD LOG] - uid:{$uid},t_id:{$target_id},type:{$type},money:{$money}", 'INFO');
        if (!$type || !$target_id || !$money) {
            return false;
        }
        switch ($type) {
            case 'video':
                $service = service('video');
                break;
            case 'comment':
                $service = service('comments');
                break;
        }
        $service && $object = $service->find($target_id);

        if (empty($object)) {
            return false;
        }

        if ($object['uid'] == $uid) {
            return [
                'code' => 501,
                'info' => '不能打赏自己',
            ];
        }

        $params = [
            'uid' => $uid,
            'target_uid' => $object['uid'],
            'money' => $money,
            'object_id' => $target_id,
            'object_type' => $type,
        ];

        \Think\Log::record('[REWARD LOG] - PUSH'.json_encode($params), "INFO");
        $res = event('LocalClient')->doRequest('reward', $params);

        if ($res['code'] == 200) {
            $data = $params;
            $data['create_time'] = NOW_TIME;
            service('RewardLog')->add($data);

            // 上报用户操作，用于显示红点
                $params = [
                    ['uid' => $uid, 'actions' => ['reward_reward']],
                    ['uid' => $target_id, 'actions' => ['reward_gain']]
                ];
                event('LocalClient')->doRequest('reddot', ['data' => json_encode($params)]);

            $userlist = empty($object['reward_users']) ? [] : $object['reward_users'];

            $user = service('users')->find($uid);
            if (!empty($user)) {
                $userlist[] = $user['nickname'];
                $service->save([
                    'id' => $target_id,
                    'reward_users' => $userlist,
                    'reward_total' => ['inc', $money],
                ]);
            }

            $this->push($user, $object['uid'], $type, $object, $money);
        }

        return $res;
    }

    /**
     * 查询用户信息
     * @author liubo <liubo@ilongyuan.com.cn>
     * @param  integer $uid 用户id
     */
    public function userinfo($uid)
    {
        $params = ['uid' => $uid];
        $res = event('LocalClient')->doRequest('userinfo', $params, 'get');

        if ($res && $res['code'] == 200) {
            return $res['data'];
        }
        return false;
    }

    /**
     * 打赏列表查询
     * @author liubo <liubo@ilongyuan.com.cn>
     * @param  string   $type  类型
     * @param  integer  $id
     * @param  integer  $p
     * @param  integer  $limit
     */
    public function lists($type, $id, $p = 0, $limit = 0)
    {
        $rService = service('RewardLog');
        $typelist = [
            'video'   => ['id' => intval($id), 'primary_key' => 'id',  'service' => 'video'],
            'comment' => ['id' => intval($id), 'primary_key' => 'id',  'service' => 'comments'],
            'threads' => ['id' => strval($id), 'primary_key' => '_id', 'service' => 'threads'],
            'posts'   => ['id' => strval($id), 'primary_key' => '_id', 'service' => 'posts'],
        ];
        if (!in_array($type, array_keys($typelist))) {
            return false;
        }
        extract($typelist[$type]);
        $map = [
            'object_type' => $type,
            'object_id'   => $id
        ];
        $total = $rService->where($map)->count();
        $query = $rService->where($map);
        if (!empty($p) && !empty($limit)) {
            $query->page($p)->limit($limit);
        }

        $list = $query->order('money desc')->field('uid,money,create_time')->select();

        $uEvent = event('user');
        $ufield = 'id,nickname,avatar'; // 用户数据字段
        foreach ($list as &$value) {
            $user = $uEvent->info($value['uid'], false, $ufield, false);
            $value['user'] = $user;
        }

        $obj = service($service)->where([$primary_key => $id])->field('id,reward_users')->find();
        $user_count = 0;
        if (!empty($obj) && !empty($obj['reward_users'])) {
            $user_count = count(array_unique($obj['reward_users']));
        }

        return ['lists' => $list ? array_values($list) : [], 'total' => ($total?:0), 'user_count' => $user_count];
    }

    /**
     * 打赏/被打赏记录
     * @author liubo <liubo@ilongyuan.com.cn>
     * @param  integer $uid 用户id
     * @param  boolean $isRecive 收到/支出
     * @param  integer $p
     * @param  integer $limit
     */
    public function record($uid, $isRecive = true, $p = 0, $limit = 0)
    {
        $object_type_map = [
            'video' => '视频',
            'comment' => '评论',
            'threads' => '帖子',
            'posts' => '回帖',
        ];
        $rService = service('RewardLog');
        if ($isRecive) {
            $map['target_uid'] = $uid;
            $user_count = count($rService->distinct('uid', $map));
        } else {
            $map['uid'] = $uid;
            $user_count = count($rService->distinct('target_uid', $map));
        }

        $total = $rService->where($map)->count();
        $query = $rService->where($map)->order('create_time desc');
        if (!empty($p) && !empty($limit)) {
            $query->page($p)->limit($limit);
        }
        $list = $query->field('uid,target_uid,target_id,object_type,money,create_time')
                         ->select();

        $uEvent = event('user');
        $ufield = 'id,nickname,avatar'; // 用户数据字段
        $ukey = $isRecive ? 'uid' : 'target_uid';
        foreach ($list as &$value) {
            $user = $uEvent->info($value[$ukey], false, $ufield, false);
            $value['user'] = $user;
            $value['object_type_text'] = empty($object_type_map[$value['object_type']]) ? '' : $object_type_map[$value['object_type']];
        }

        return ['lists' => array_values($list), 'total' => ($total?:0), 'user_count' => $user_count];
    }

    /**
     * 打赏推送
     * @author liubo <liubo@ilongyuan.com.cn>
     * @param  array   $uid         打赏者
     * @param  integer $target_uid  被打赏者id
     * @param  string  $object_type 打赏类型
     * @param  integer $object      打赏对象
     * @param  integer $money       打赏金额
     */
    private function push($user, $target_uid, $object_type, $object, $money)
    {
        $pEvent = event('push');
        $uService = service('users');
        $from = $user;
        $to = $uService->find($target_uid);

        if (!$from || !$to) {
            return;
        }
        // 全服通告
        $push_line = intval(C('REWARD_PUSH_LINE', null, 666));
        $global = $money >= $push_line;
        \Think\Log::record('[REWARD LOG PUSH] - '.$from['nickname'].' '.$to['nickname'], 'INFO');
        // 推送
        $to = [
            'uid' => $to['id'],
            'nickname' => $to['nickname']
        ];
        $pEvent->reward($from, $to, $object_type, $money, $object, $global);

    }

    public function total($filter = [], $group = 'id')
    {
        $res = service('RewardLog')->total($filter, $group, 'money');
        return empty($res) ? [] : array_column($res, 'total', $group);
    }
}
